
package src;

import com.google.api.translate.Language;
import com.google.api.translate.Translate;
import com.google.gdata.util.ServiceException;
import java.awt.AWTException;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.Point;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * QuicklyTranslatorFrame.java
 *
 * Created on Mar 11, 2009, 10:33:01 PM
 */
/**
 *
 * @author Administrador
 */
public class QuicklyTranslatorFrame extends javax.swing.JFrame implements ClipboardOwner
{
    public static String VERSION = "0.13RC";
    public static int CONFIGURATEDSTARTKEY = 1; //1 space 2 enter
    private String originalText = "";
    private String lastTypedWord = null;
    private int caractCountAtProcessStart = 0;
    private Character lastCharactTyped = ' ';
    private int pos;
    private Point p = null,  o = null;
    private char lastPressedKey = 0;
    private boolean byPastWays = false;
    private TrayIcon trayIcon;
    private boolean added = false;
    private int lasTec1 = -1;
    private int lasTec0 = -1;
    private WriteProprierts w;
    private String AUTOMATIC = "Automatic Detector";

    /** Creates new form QuicklyTranslatorFrame */
    public QuicklyTranslatorFrame()
    {
        initComponents();

        box.setLineWrap( true );

        setTitle( "QuicklyTranslator " + VERSION );
        createTrayIcon();
        setDefaultCloseOperation( HIDE_ON_CLOSE );

        RegisterCopy reg = new RegisterCopy();
        reg.start();

        //get email person

        listTo.addItem( AUTOMATIC );
        listTo.setVisible( false );
        jLabel3.setText( AUTOMATIC );
        jLabel3.setVisible( true );


        for ( LanguageName l : LanguageName.values() )
        {
            listTo.addItem( l.getAlias() );
        }

        listTo.setSelectedItem( AUTOMATIC );

        Dimension dim = java.awt.Toolkit.getDefaultToolkit().getScreenSize();

        String vendor = System.getProperty( "os.name" );

        int posX = 0;
        int posY = 0;

        if ( vendor.equals( "Linux" ) )
        {
            posX = ( ( dim.width ) - ( getSize().width / 2 ) );
            posY = ( ( dim.height ) - ( getSize().height / 2 ) );
        }
        else
        {
            posX = ( ( dim.width ) - ( getSize().width ) );
            posY = ( ( dim.height ) - ( getSize().height + 30 ) );
        }

        setLocation( posX, posY );

        Degub.getInstance().Debug( "Type in portugues to translate to english \nTyping in any other language it will be translated to Portugues.. \nTwo click at one word to open definitions \nPress space to auto translate any word in any language \nPress F1 to see the Degub.. \nPress alt to see original text \nPress control + V to past and automatic translate \n Link http://spreadsheets.google.com/pub?key=p5IcvKLJhtl2MqAZSa0Fvbg&hl=pt_BR" );

        adicionarListeners();

        setVisible( true );

        w = new WriteProprierts();

        addToTray();
    }

    private void clear()
    {
        originalText = "";
        box.setText( originalText );
        listTo.setSelectedIndex( 0 );
        listTo.setVisible( false );
        jLabel3.setVisible( true );
        jLabel3.setText( AUTOMATIC );
        autoTranslateButton.setSelected( true );
    }

    private String getToIdiom()
    {
        String ax = "";
        for ( LanguageName l : LanguageName.values() )
        {
            if ( l.getAlias().equals( listTo.getSelectedItem() ) )
            {
                ax = l.toString();
            }
        }

        return ax;
    }

    private void setToIdiom( String l )
    {
        for ( LanguageName n : LanguageName.values() )
        {
            if ( n.toString().equals( l ) )
            {
                listTo.setSelectedItem( n.getAlias() );
            }
        }
    }

    private void traduzAgainToOtherIdiom()
    {
        Degub.getInstance().Debug( "Translating by combo" );
        {
            TraduzThread t = new TraduzThread( originalText );
            t.start();
        }
    }

    /**
     * adicionarListeners
     *
     */
    private void adicionarListeners()
    {

        listTo.addActionListener( new ActionListener()
        {

            public void actionPerformed( ActionEvent e )
            {
                if ( listTo.getSelectedItem().equals( AUTOMATIC ) )
                {
                    listTo.setVisible( false );
                    jLabel3.setVisible( true );
                    autoTranslateButton.setSelected( true );
                    traduzAgainToOtherIdiom();
                }

                if ( listTo.isShowing() )
                {
                    byPastWays = true;
                    traduzAgainToOtherIdiom();
                }

                if ( autoTranslateButton.isSelected() )
                {
                    listTo.setVisible( false );
                    jLabel3.setVisible( true );
                    jLabel3.setText( listTo.getSelectedItem().toString() );
                }
            }
        } );

        clearButton.addActionListener( new ActionListener()
        {

            public void actionPerformed( ActionEvent e )
            {
                clear();
            }
        } );

        addWindowListener( new WindowAdapter()
        {

            @Override
            public void windowIconified( WindowEvent e )
            {
                addToTray();
            }
        } );

        box.addKeyListener( new KeyListener()
        {

            String helpVar;
            int wordNum;
            //String word = "";

            public void keyTyped( KeyEvent e )
            {
                try
                {
                    if ( e.getKeyChar() == '\b' )
                    {
                        clearOriginalText();
                        jLabel1.setText( "Original Text" );
                    }

                    if ( e.getKeyChar() == ' ' || e.getKeyChar() == '\n' )
                    {
                        int lastSpace = ( box.getText().trim().lastIndexOf( " " ) == -1 ) ? 0 : box.getText().trim().lastIndexOf( " " );
                        lastTypedWord = box.getText().substring( lastSpace, box.getText().length() ).trim();
                        lastPressedKey = e.getKeyChar();
                        caractCountAtProcessStart = originalText.length();

                        Degub.getInstance().Debug( "Getting up word: " + originalText );
                        Degub.getInstance().Debug( "ConfigurationKey = " + CONFIGURATEDSTARTKEY );

                        CONFIGURATEDSTARTKEY = Integer.valueOf( w.read( WriteProprierts.STARTKEY ) );
                    }

                    if ( CONFIGURATEDSTARTKEY < 2 )
                    {
                        //Its here that start all the process of translation
                        if ( e.getKeyChar() == ' ' )
                        {
                            Degub.getInstance().Debug( "if ( CONFIGURATEDSTARTKEY < 2 )" );

                            if ( listTo.isShowing() || ( !jLabel3.getText().equals( AUTOMATIC ) ) )
                            {
                                TransPureWord trans = new TransPureWord( originalText );
                                trans.start();
                            }
                            else
                            {
                                TraduzThread tr = new TraduzThread( originalText );
                                Degub.getInstance().Debug( "Starting thread " + tr.getName() + " to translate " + originalText );
                                tr.start();
                            }
                        }
                    }
                    else if ( CONFIGURATEDSTARTKEY == 2 )
                    {
                        //Its here that start all the process of translation
                        if ( e.getKeyChar() == '\n' )
                        {
                            Degub.getInstance().Debug( "else if ( CONFIGURATEDSTARTKEY == 2 )" );

                            TraduzThread tr = new TraduzThread( originalText );
                            Degub.getInstance().Debug( "Starting thread " + tr.getName() + " to translate " + originalText );
                            tr.start();
                        }
                    }
                    else
                    {
                        if ( box.getText().isEmpty() )
                        {
                            originalText = "";
                        }


                    }

                    if ( e.getKeyChar() != '\n' && e.getKeyChar() != '\b' )
                    {
                        originalText += e.getKeyChar();
                        Degub.getInstance().Debug( "" + e.getKeyChar() );

                        if ( e.getKeyChar() != ' ' )
                        {
                            lastCharactTyped = e.getKeyChar();
                        }
                    }


                }
                catch ( Exception ex )
                {
                    Degub.getInstance().Debug( ex );
                }
            }

            @Override
            public void keyPressed( KeyEvent e )
            {
                //if alt, show digited text
                if ( e.getKeyCode() == 18 )
                {
                    helpVar = box.getText();
                    box.setText( originalText );
                    jLabel1.setText( "Original Text" );
                }
                else if ( e.getKeyCode() == 112 )
                {
                    Degub.getInstance().debugShow();
                }
            }
            int i;

            @Override
            public void keyReleased( KeyEvent e )
            {
                if ( e.getKeyCode() == 18 )
                {
                    box.setText( helpVar );
                }

                lasTec0 = lasTec1;
                lasTec1 = e.getKeyCode();

                //control v
                if ( lasTec0 == 17 )
                {
                    if ( e.getKeyCode() == 86 )
                    {
                        try
                        {
                            Degub.getInstance().Debug( "Texto Colado.. Aguarde.." );
                            translatePastedData();
                        }
                        catch ( UnsupportedFlavorException ex )
                        {
                            Degub.getInstance().Debug( ex.getMessage() );
                        }
                        catch ( IOException ex )
                        {
                            Degub.getInstance().Debug( ex.getMessage() );
                        }
                    }
                }



                box.setSelectedTextColor( Color.black );
            }
        } );

        box.addMouseListener( new MouseListener()
        {

            public void mouseClicked( MouseEvent e )
            {
                pos++;
                o = p;
                p = e.getPoint();

                if ( box.getText().length() != 0 )
                {
                    if ( box.getSelectedText() != null )
                    {
                        if ( box.getSelectedText().length() > 1 )
                        {
                            box.setCursor( Cursor.getPredefinedCursor( Cursor.HAND_CURSOR ) );

                            if ( pos > 1 && o.equals( p ) )
                            {
                                //OpenLowBrowser opne = new OpenLowBrowser( "http://www.google.com/dictionary?aq=f&langpair=" + getToIdiom() + "|" + getToIdiom() + "&q=" + box.getSelectedText()  + "&hl=pt-BR" );
                                //OpenLowBrowser opne = new OpenLowBrowser( "http://www.google.com/dictionary?langpair=" + getToIdiom() + "|" + getToIdiom() + "&q=test&hl=" + box.getSelectedText() + "&aq=f" );
                                //opne.start();
                                new GetSourceCodeFromHTML( box.getSelectedText() );
                                box.setCursor( Cursor.getPredefinedCursor( Cursor.HAND_CURSOR ) );
                                box.setSelectedTextColor( Color.red );


                            }
                        }
                    }
                }
            }

            public void mousePressed( MouseEvent e )
            {
            }

            public void mouseReleased( MouseEvent e )
            {
            }

            public void mouseEntered( MouseEvent e )
            {
                pos = 0;
                box.setCursor( Cursor.getDefaultCursor() );
            }

            public void mouseExited( MouseEvent e )
            {
                pos = 0;
                box.setCursor( Cursor.getDefaultCursor() );
            }
        } );

        box.addMouseMotionListener( new MouseMotionListener()
        {

            public void mouseDragged( MouseEvent e )
            {
            }

            public void mouseMoved( MouseEvent e )
            {
                pos = 0;
                box.setCursor( Cursor.getDefaultCursor() );
            }
        } );

        this.addWindowListener( new WindowAdapter()
        {

            public void windowIconified( WindowEvent ev )
            {
                if ( ev.getID() == WindowEvent.WINDOW_ICONIFIED )
                {
                    clear();
                }
            }
        } );
    }

    public void openDefinitionHTMLWindow( String from, String to, String text, String defaultLanguage ) throws Exception
    {
        Degub.getInstance().Debug( "Opening window html definitions: " + from + " - " + to + " - " + text );
        new GetSourceCodeFromHTML( text );

    }

    public void clearOriginalText()
    {
        originalText = originalText.substring( 0, originalText.length() - 1 );
        box.setText( originalText );
    }

    public boolean hasUnknowingCaracters( String txt )
    {
        return ( txt.indexOf( "&#39;" ) == -1 ? false : true );
    }

    public String clearUnknowingCacacters( String txt )
    {
        while ( hasUnknowingCaracters( txt ) )
        {
            if ( txt.indexOf( "&#39;" ) != -1 )
            {
                String or = txt;
                txt = txt.substring( 0, txt.indexOf( "&#39;" ) );
                txt = txt + "'" + or.substring( or.indexOf( "&#39;" ) + 5, or.length() );
                Degub.getInstance().Debug( "Retirando caracteres idiotas: " + txt + " - " + or );
            }
        }

        return txt;
    }

    class TransPureWord extends Thread
    {

        String word;
        String translated;

        public TransPureWord( String word )
        {
            this.word = word;

        }

        public String getTranslated()
        {
            return this.translated;
        }

        @Override
        public void run()
        {
            try
            {
                translated = translate( word, "", getToIdiom() );

                setTranslatedText( translated );
            }
            catch ( Exception ex )
            {
                Degub.getInstance().Debug( ex.getMessage() );
            }
        }
    }
    TraduzThread lastThread = null;
    int threadCount = 0;

    public String translate( String word, String from, String to ) throws Exception
    {
        String trans = Translate.translate( word, from, to );
        return clearUnknowingCacacters( trans );
    }

    /**
     * TraduzThread
     *
     * @return class
     * @ignored extends
     * @ignored Thread
     */
    class TraduzThread extends Thread
    {

        public boolean alive = true;
        String phrase = "";

        private TraduzThread( String phrase )
        {
            this.phrase = phrase.trim();
        }

        @Override
        public void run()
        {
            if ( lastThread != null )
            {
                if ( lastThread.isAlive() )
                {
                    Degub.getInstance().Debug( "Killing last thread " + lastThread.getName() );
                    lastThread.suspend();
                }
            }

            threadCount++;
            lastThread = this;

            int y = box.getVisibleRect().height;
            int x = box.getVisibleRect().width;

//            //box.setColors( new Color( 245, 255, 245 ), Color.white );
//
//            ////box.setTransition( 0, 0, x, 0 );

            try
            {
                String translated = null;

                try
                {
                    if ( !listTo.isShowing() )
                    {
                        Degub.getInstance().Debug( "AUTOTRANS 1: Starting deciding exiting idiom" );

                        if ( ( jLabel3.getText().equals( AUTOMATIC ) || threadCount % 4 == 0 ) && ( phrase.trim().length() > 0 ) )
                        {
                            Degub.getInstance().Debug( "AUTOTRANS 2: Deciding what is the out idiom... (" + phrase + ")" );

                            // se o texto for grande, contar as palavras e pegar uma no meio p verificar
                            String firstWord = phrase;

                            if ( phrase.trim().indexOf( " " ) > 0 )
                            {
                                firstWord = phrase.substring( 0, phrase.trim().indexOf( " " ) );
                            }
                            //
                            translated = translate( firstWord, Language.PORTUGESE, Language.ENGLISH );

                            Degub.getInstance().Debug( "AUTOTRANS 3: Decided what is the out idiom... (" + firstWord + ")" );

                            translated = clearUnknowingCacacters( translated );

                            Degub.getInstance().Debug( "AUTOTRANS 4: " + translated + " is equals " + firstWord );

                            if ( !translated.equalsIgnoreCase( firstWord.trim() ) )
                            {
                                setToIdiom( Language.ENGLISH );
                                Degub.getInstance().Debug( "AUTOTRANS 5: No - its english" );
                            }
                            else
                            {
                                setToIdiom( Language.PORTUGESE );
                                Degub.getInstance().Debug( "AUTOTRANS 5: Yes - Its portuguese" );
                            }

                            //registro de tradução
                            int a = Integer.valueOf( w.read( WriteProprierts.RANKING ) ) + threadCount;
                            w.write( WriteProprierts.RANKING, String.valueOf( a ) );
                        }
                    }

                    //box.setTransition( x / 2, 0, x, 0 );

                    Degub.getInstance().Debug( "AUTOTRANS 6: Traduzindo " + phrase + " para: " + listTo.getSelectedItem() );

                    translated = translate( phrase, "", getToIdiom() );

                    translated = clearUnknowingCacacters( translated );

                    //box.setTransition( 0, 0, 0, 0 );
                    //box.setColors( Color.white, Color.white );

                    Degub.getInstance().Debug( "AUTOTRANS 7: " + translated );
                }
                catch ( Exception ex )
                {
                    Degub.getInstance().Debug( ex.getMessage() );
                }

                int lastSpace = ( box.getText().trim().lastIndexOf( " " ) == -1 ) ? 0 : box.getText().trim().lastIndexOf( " " );


                Degub.getInstance().Debug( "Contagem total de caracteres no comeco do processo: " + caractCountAtProcessStart + " Atual " + box.getText().length() );
                //System.out.println( "Contagem total de caracteres no comeco do processo: " + caractCountAtProcessStart + " Atual " + box.getText().length() );

                Degub.getInstance().Debug( "Finalizando thread " + this.getName() );
                //System.out.println( "Finalizando thread " + this.getName() );

                setTranslatedText( translated );
            }

            catch ( Exception ex )
            {
                Degub.getInstance().Debug( "Cannot access Google.com database... \n" + ex + "\n Verify your internet connection" );
            }

        }
    }

    private void createTrayIcon()
    {
        createTrayIcon( Toolkit.getDefaultToolkit().getImage( getClass().getResource( "/res/world_globe.png" ) ) );
    }

    private void createTrayIcon( Image icon )
    {
        SystemTray tray = SystemTray.getSystemTray();
        if ( !SystemTray.isSupported() )
        {
            Degub.getInstance().Debug( "Não é possível executar a app" );
            System.exit( 0 );
        }        

        icon.getScaledInstance( tray.getTrayIconSize().height, tray.getTrayIconSize().width, Image.SCALE_SMOOTH );

        PopupMenu menu = new PopupMenu();
        MenuItem itemRestaurar = new MenuItem( "Restaurar" );
        itemRestaurar.addActionListener( new ActionListener()
        {

            @Override
            public void actionPerformed( ActionEvent e )
            {
                setVisible( true );
            }
        } );

        MenuItem itemSair = new MenuItem( "Sair" );
        itemSair.addActionListener( new ActionListener()
        {

            @Override
            public void actionPerformed( ActionEvent e )
            {
                System.exit( 0 );
            }
        } );

        menu.add( itemRestaurar );
        menu.add( itemSair );

        trayIcon = new TrayIcon( icon, "QuicklyTranslator", menu );
        trayIcon.addMouseListener( new MouseAdapter()
        {

            @Override
            public void mouseClicked( MouseEvent e )
            {
                if ( e.getClickCount() == 1 )
                {
                    setVisible( true );
                    originalText = "";
                    box.setText( originalText );
                    box.selectAll();
                }
            }
        } );
    }

    public void translatePastedData() throws UnsupportedFlavorException, IOException
    {
        byPastWays = true;

        TraduzThread tra = new TraduzThread( box.getText() );
        Degub.getInstance().Debug( "Traduzir clipboard: " + box.getText() );
        originalText = box.getText();

        tra.start();
    }

    private void addToTray()
    {
        try
        {
            dispose();

            if ( !added )
            {
                trayIcon.displayMessage( "QuicklyTranslator running..", "Click over the icon, to open..", TrayIcon.MessageType.INFO );
                SystemTray.getSystemTray().add( trayIcon );
                added = true;

                listTo.setVisible( false );
                jLabel3.setVisible( true );
                jLabel3.setText( AUTOMATIC );

            }

        }
        catch ( AWTException ex )
        {
            Degub.getInstance().Debug( ex.getMessage() );
        }
    }

    //used to set text when we need to verify if user are still typing..
    public void setTranslatedText( String txt )
    {
        int lastSpace = ( box.getText().trim().lastIndexOf( " " ) == -1 ) ? 0 : box.getText().trim().lastIndexOf( " " );
        String lastWordofBox = box.getText().substring( lastSpace, box.getText().length() ).trim();

        Degub.getInstance().Debug( "SET 1: Verifying Process" );

        if ( lastPressedKey == ' ' || lastPressedKey == '\n' || byPastWays || CONFIGURATEDSTARTKEY == 2 )
        {
            Degub.getInstance().Debug( "SET 2: if ( lastWordofBox.equals( lastTypedWord ) ) " + lastTypedWord );

            if ( lastWordofBox.equals( lastTypedWord ) || CONFIGURATEDSTARTKEY == 2 )
            {
                Character lastCharOfOriginalText = originalText.trim().charAt( originalText.trim().length() - 1 );

                Degub.getInstance().Debug( "SET 3: if ( caractCountAtProcessStart + 1 == originalText.length() || byPastWays || CONFIGURATEDSTARTKEY == 2 || lastCharactTyped == lastCharOfOriginalText ) " + caractCountAtProcessStart + 1 + " - " + originalText.length() + " - " + lastCharOfOriginalText + " - " + lastCharactTyped );

                if ( caractCountAtProcessStart + 1 == originalText.length() || byPastWays || CONFIGURATEDSTARTKEY == 2 || lastCharactTyped == lastCharOfOriginalText )
                {
                    Degub.getInstance().Debug( "SET 4: Setting translated text: " + txt );
                    box.setText( txt + " " );
                    box.setCaretPosition( box.getText().length() );
                    Degub.getInstance().Debug( "SET 5: Texto Traduzido!" );

                }
            }
            else
            {
                Degub.getInstance().Debug( lastWordofBox + " its different of " + lastTypedWord );
            }
        }
        else
        {
            Degub.getInstance().Debug( "\n" + "Ainda não é hora de traduzir" );
            Degub.getInstance().Debug( "Aguardando para traduzir, precione 'Espaço' para concluir!" );
        }

        byPastWays = false;
    }

    class RegisterCopy extends Thread
    {

        private RegisterCopy()
        {
        }

        public void run()
        {
            Degub.getInstance().Debug( "Registering your copy usage..." );
            ComputeUsage c = new ComputeUsage();
            c.ComputeUsage();
            c.setData();
            try
            {
                try
                {
                    if ( c.needUpdate() )
                    {
                        trayIcon.displayMessage( "QuicklyTranslator updating..", "We are downloading the last version.. don't close the program now", TrayIcon.MessageType.INFO );
                        SystemTray.getSystemTray().remove( trayIcon );
                        added = false;
                        createTrayIcon( Toolkit.getDefaultToolkit().getImage( getClass().getResource( "/res/world_globe_sel.png" ) ) );
                        addToTray();

                        c.processUpdate();

                        SystemTray.getSystemTray().remove( trayIcon );
                        added = false;
                        createTrayIcon();
                        addToTray();
                        trayIcon.displayMessage( "QuicklyTranslator Updated..", "You have the last version, restart the program to apply the changes..", TrayIcon.MessageType.INFO );
                    }
                }
                catch ( ServiceException ex )
                {
                    Degub.getInstance().Debug( ex );
                }
            }
            catch ( IOException ex )
            {
                Degub.getInstance().Debug( ex );
            }

        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings( "unchecked" )
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents()
    {

        jPanel1 = new javax.swing.JPanel();
        jToolBar1 = new javax.swing.JToolBar();
        configurationButton = new javax.swing.JButton();
        processButton = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        jSeparator3 = new javax.swing.JToolBar.Separator();
        clearButton = new javax.swing.JButton();
        jSeparator4 = new javax.swing.JToolBar.Separator();
        jSeparator2 = new javax.swing.JToolBar.Separator();
        cutButton = new javax.swing.JButton();
        copyButton = new javax.swing.JButton();
        pasteButton = new javax.swing.JButton();
        jSeparator5 = new javax.swing.JToolBar.Separator();
        jSeparator6 = new javax.swing.JToolBar.Separator();
        heltpButton = new javax.swing.JButton();
        autoTranslateButton = new javax.swing.JToggleButton();
        lblTranslating = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        listTo = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        box = new src.JTextAreaWithBackground();

        setDefaultCloseOperation( javax.swing.WindowConstants.EXIT_ON_CLOSE );
        getContentPane().setLayout( new javax.swing.BoxLayout( getContentPane(), javax.swing.BoxLayout.LINE_AXIS ) );

        jToolBar1.setBorder( null );
        jToolBar1.setFloatable( false );
        jToolBar1.setRollover( true );
        jToolBar1.setDebugGraphicsOptions( javax.swing.DebugGraphics.NONE_OPTION );
        jToolBar1.setOpaque( false );

        configurationButton.setIcon( new javax.swing.ImageIcon( getClass().getResource( "/res/tool.png" ) ) ); // NOI18N
        configurationButton.setToolTipText( "Configurações" );
        configurationButton.setBorder( null );
        configurationButton.setFocusable( false );
        configurationButton.setHorizontalTextPosition( javax.swing.SwingConstants.CENTER );
        configurationButton.setVerticalTextPosition( javax.swing.SwingConstants.BOTTOM );
        configurationButton.addActionListener( new java.awt.event.ActionListener()
        {

            public void actionPerformed( java.awt.event.ActionEvent evt )
            {
                configurationButtonActionPerformed( evt );
            }
        } );
        jToolBar1.add( configurationButton );

        processButton.setIcon( new javax.swing.ImageIcon( getClass().getResource( "/res/process.png" ) ) ); // NOI18N
        processButton.setToolTipText( "Processos" );
        processButton.setBorder( null );
        processButton.setFocusable( false );
        processButton.setHorizontalTextPosition( javax.swing.SwingConstants.CENTER );
        processButton.setVerticalTextPosition( javax.swing.SwingConstants.BOTTOM );
        processButton.addActionListener( new java.awt.event.ActionListener()
        {

            public void actionPerformed( java.awt.event.ActionEvent evt )
            {
                processButtonActionPerformed( evt );
            }
        } );
        jToolBar1.add( processButton );
        jToolBar1.add( jSeparator1 );
        jToolBar1.add( jSeparator3 );

        clearButton.setIcon( new javax.swing.ImageIcon( getClass().getResource( "/res/trash.png" ) ) ); // NOI18N
        clearButton.setToolTipText( "Limpar" );
        clearButton.setBorder( null );
        clearButton.setFocusable( false );
        clearButton.setHorizontalTextPosition( javax.swing.SwingConstants.CENTER );
        clearButton.setVerticalTextPosition( javax.swing.SwingConstants.BOTTOM );
        jToolBar1.add( clearButton );
        jToolBar1.add( jSeparator4 );
        jToolBar1.add( jSeparator2 );

        cutButton.setIcon( new javax.swing.ImageIcon( getClass().getResource( "/res/cut.png" ) ) ); // NOI18N
        cutButton.setToolTipText( "Recortar" );
        cutButton.setBorder( null );
        cutButton.setFocusable( false );
        cutButton.setHorizontalTextPosition( javax.swing.SwingConstants.CENTER );
        cutButton.setVerticalTextPosition( javax.swing.SwingConstants.BOTTOM );
        cutButton.addActionListener( new java.awt.event.ActionListener()
        {

            public void actionPerformed( java.awt.event.ActionEvent evt )
            {
                cutButtonActionPerformed( evt );
            }
        } );
        jToolBar1.add( cutButton );

        copyButton.setIcon( new javax.swing.ImageIcon( getClass().getResource( "/res/folder.png" ) ) ); // NOI18N
        copyButton.setToolTipText( "Copiar" );
        copyButton.setBorder( null );
        copyButton.setFocusable( false );
        copyButton.setHorizontalTextPosition( javax.swing.SwingConstants.CENTER );
        copyButton.setVerticalTextPosition( javax.swing.SwingConstants.BOTTOM );
        copyButton.addActionListener( new java.awt.event.ActionListener()
        {

            public void actionPerformed( java.awt.event.ActionEvent evt )
            {
                copyButtonActionPerformed( evt );
            }
        } );
        jToolBar1.add( copyButton );

        pasteButton.setIcon( new javax.swing.ImageIcon( getClass().getResource( "/res/note.png" ) ) ); // NOI18N
        pasteButton.setToolTipText( "Colar" );
        pasteButton.setBorder( null );
        pasteButton.setFocusable( false );
        pasteButton.setHorizontalTextPosition( javax.swing.SwingConstants.CENTER );
        pasteButton.setVerticalTextPosition( javax.swing.SwingConstants.BOTTOM );
        pasteButton.addActionListener( new java.awt.event.ActionListener()
        {

            public void actionPerformed( java.awt.event.ActionEvent evt )
            {
                try
                {
                    pasteButtonActionPerformed( evt );
                }
                catch ( ClassNotFoundException ex )
                {
                    Degub.getInstance().Debug( ex );
                }
            }
        } );
        jToolBar1.add( pasteButton );
        jToolBar1.add( jSeparator5 );
        jToolBar1.add( jSeparator6 );

        heltpButton.setIcon( new javax.swing.ImageIcon( getClass().getResource( "/res/help.png" ) ) ); // NOI18N
        heltpButton.setToolTipText( "Help" );
        heltpButton.setBorder( null );
        heltpButton.setFocusable( false );
        heltpButton.setHorizontalTextPosition( javax.swing.SwingConstants.CENTER );
        heltpButton.setVerticalTextPosition( javax.swing.SwingConstants.BOTTOM );
        heltpButton.addActionListener( new java.awt.event.ActionListener()
        {

            public void actionPerformed( java.awt.event.ActionEvent evt )
            {
                heltpButtonActionPerformed( evt );
            }
        } );
        jToolBar1.add( heltpButton );

        autoTranslateButton.setIcon( new javax.swing.ImageIcon( getClass().getResource( "/res/world_globe.png" ) ) ); // NOI18N
        autoTranslateButton.setSelected( true );
        autoTranslateButton.setBorder( null );
        autoTranslateButton.setFocusable( false );
        autoTranslateButton.setHorizontalTextPosition( javax.swing.SwingConstants.CENTER );
        autoTranslateButton.setSelectedIcon( new javax.swing.ImageIcon( getClass().getResource( "/res/world_globe_sel.png" ) ) ); // NOI18N
        autoTranslateButton.setVerticalTextPosition( javax.swing.SwingConstants.BOTTOM );
        autoTranslateButton.addActionListener( new java.awt.event.ActionListener()
        {

            public void actionPerformed( java.awt.event.ActionEvent evt )
            {
                autoTranslateButtonActionPerformed( evt );
            }
        } );
        jToolBar1.add( autoTranslateButton );

        lblTranslating.setFont( lblTranslating.getFont().deriveFont( lblTranslating.getFont().getStyle() & ~java.awt.Font.BOLD ) );
        lblTranslating.setText( "Translating to: " );
        jToolBar1.add( lblTranslating );

        jLabel3.setFont( jLabel3.getFont().deriveFont( jLabel3.getFont().getStyle() | java.awt.Font.BOLD ) );
        jLabel3.setText( "jLabel3" );
        jToolBar1.add( jLabel3 );

        jToolBar1.add( listTo );

        jLabel1.setFont( jLabel1.getFont().deriveFont( jLabel1.getFont().getStyle() & ~java.awt.Font.BOLD ) );
        jLabel1.setText( "Waiting to type..." );

        box.setColumns( 20 );
        box.setRows( 5 );
        jScrollPane1.setViewportView( box );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout( jPanel1 );
        jPanel1.setLayout( jPanel1Layout );
        jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING ).addGroup( javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup().addGroup( jPanel1Layout.createParallelGroup( javax.swing.GroupLayout.Alignment.TRAILING ).addGroup( jPanel1Layout.createSequentialGroup().addContainerGap().addComponent( jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 470, Short.MAX_VALUE ) ).addGroup( javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup().addContainerGap().addComponent( jLabel1 ) ).addGroup( javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup().addContainerGap().addComponent( jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 470, Short.MAX_VALUE ) ) ).addContainerGap() ) );
        jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING ).addGroup( jPanel1Layout.createSequentialGroup().addComponent( jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE ).addGap( 1, 1, 1 ).addComponent( jLabel1 ).addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED ).addComponent( jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 110, Short.MAX_VALUE ).addContainerGap() ) );

        getContentPane().add( jPanel1 );

        pack();
    }// </editor-fold>                        

    private void configurationButtonActionPerformed( java.awt.event.ActionEvent evt )
    {
        Configurations r = new Configurations();
    }

    private void autoTranslateButtonActionPerformed( java.awt.event.ActionEvent evt )
    {
        if ( !autoTranslateButton.isSelected() )
        {
            lblTranslating.setText( " Translating to: " );
            listTo.setVisible( true );
            jLabel3.setVisible( false );
        }
        else
        {
            lblTranslating.setText( " Translating to: " );
            listTo.setVisible( false );
            jLabel3.setVisible( true );
            jLabel3.setText( AUTOMATIC );
        }
    }

    private void heltpButtonActionPerformed( java.awt.event.ActionEvent evt )
    {
        TesteAbout a = new TesteAbout();
        a.setVisible( true );
    }

    private void processButtonActionPerformed( java.awt.event.ActionEvent evt )
    {
        Degub.getInstance().debugShow();
    }

    private void cutButtonActionPerformed( java.awt.event.ActionEvent evt )
    {

        copyButtonActionPerformed( evt );

        box.setText( "" );
    }

    public void lostOwnership( Clipboard clip, Transferable tr )
    {
        //System.out.println( "Lost Clipboard Ownership?!?" );
    }

    private void copyButtonActionPerformed( java.awt.event.ActionEvent evt )
    {
        SecurityManager ars = System.getSecurityManager();

        if ( ars != null )
        {
            try
            {
                ars.checkSystemClipboardAccess();
            }
            catch ( Exception e )
            {
                e.printStackTrace();
            }
        }
        Toolkit tk = Toolkit.getDefaultToolkit();

        StringSelection st = new StringSelection( box.getText().toString() );
        Clipboard cp = tk.getSystemClipboard();

        cp.setContents( st, this );
    }

    private void pasteButtonActionPerformed( java.awt.event.ActionEvent evt ) throws ClassNotFoundException
    {
        try
        {
            Toolkit tk = Toolkit.getDefaultToolkit();
            Clipboard clipboard = tk.getSystemClipboard();
            Transferable clipData = clipboard.getContents( clipboard );
            if ( clipData != null )
            {
                try
                {
                    if ( clipData.isDataFlavorSupported( DataFlavor.stringFlavor ) )
                    {
                        String s = ( String ) ( clipData.getTransferData(
                                DataFlavor.stringFlavor ) );
                        box.replaceSelection( s );
                    }
                }
                catch ( UnsupportedFlavorException ufe )
                {
                    Degub.getInstance().Debug( "Flavor unsupported: " + ufe );
                }
                catch ( IOException ioe )
                {
                    Degub.getInstance().Debug( "Data not available: " + ioe );
                }
            }
            translatePastedData();
        }
        catch ( UnsupportedFlavorException ex )
        {
            Degub.getInstance().Debug( ex );
        }
        catch ( IOException ex )
        {
            Degub.getInstance().Debug( ex );
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main( String args[] )
    {
        java.awt.EventQueue.invokeLater( new Runnable()
        {

            public void run()
            {
                new QuicklyTranslatorFrame().setVisible( true );
            }
        } );
    }

    // Variables declaration - do not modify                     
    private javax.swing.JToggleButton autoTranslateButton;
    private src.JTextAreaWithBackground box;
    private javax.swing.JButton clearButton;
    private javax.swing.JButton configurationButton;
    private javax.swing.JButton copyButton;
    private javax.swing.JButton cutButton;
    private javax.swing.JButton heltpButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator2;
    private javax.swing.JToolBar.Separator jSeparator3;
    private javax.swing.JToolBar.Separator jSeparator4;
    private javax.swing.JToolBar.Separator jSeparator5;
    private javax.swing.JToolBar.Separator jSeparator6;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JLabel lblTranslating;
    private javax.swing.JComboBox listTo;
    private javax.swing.JButton pasteButton;
    private javax.swing.JButton processButton;
    // End of variables declaration    
}

